import type {
  KoaContext,
} from '@/types/koa';

import {
  generateRandomNumber,
} from '@/tools/random';

import {
  findUser,
  createUser,
} from '@/service/user.service';

// tips 生成账号函数
const generateAccount = async () => {
  const account = generateRandomNumber(9);
  const user = await findUser({ attributes: ['id'], where: { account } });
  if (user) {
    generateAccount();
  }
  return account;
};

// tips 用户注册
export const emailRegister = async (ctx: KoaContext) => {
  const { email, password } = ctx.request.body;

  const account = await generateAccount();

  let user: any = {};
  try {
    user = await createUser({
      account,
      password: password as string,
      email,
    });
  } catch (error) {
    console.error(error);
  }

  const { password: pwd, ...u1 } = user['dataValues'];

  ctx.body = {
    code: 200,
    message: '注册成功',
    data: u1,
  };
};
export const phoneRegister = async (ctx: KoaContext) => {
  ctx.body = {
    code: 200,
    message: 'phone register user',
  };
};

// tips 用户登录
export const emailLogin = async (ctx: KoaContext) => {
  ctx.body = {
    code: 200,
    message: '登录成功',
    data: ctx.state.user,
    ...ctx.cache.login_token,
  };

  ctx.cache = {};
};
export const phoneLogin = async (ctx: KoaContext) => {
  ctx.body = {
    code: 200,
    message: 'phone login user',
  };
};
export const accountLogin = async (ctx: KoaContext) => {
  ctx.body = {
    code: 200,
    message: '登录成功',
    data: ctx.state.user,
    ...ctx.cache.login_token,
  };

  ctx.cache = {};
};
